package com.ck.common.service.impl;

import com.ck.common.service.ResolveExcelService;
import com.ck.exception.ServiceException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ResolveExcelServiceImpl
 * @Description Excel文件解析Service实现类
 * @Author HanQinrui
 * @Date 2018/7/27 15:18
 * @Version 1.0
 **/
@Service(value = "resolveExcelService")
public class ResolveExcelServiceImpl implements ResolveExcelService {

    private static final String SUFFIX_2003 = ".xls";
    private static final String SUFFIX_2007 = ".xlsx";

    /**
     * 解析Excel文档得到机器码list
     * @param file Excel文档
     * @return List<String>
     */
    @Override
    public List<String> resolveExcel(MultipartFile file) throws ServiceException {
        List<String> deviceCodeList = new ArrayList<>();
        if(file == null) {
            throw new ServiceException("上传文件不能为空");
        }
        // 获取文件名字,用来验证文件格式
        String originalFilename = file.getOriginalFilename();
        Workbook workbook = null;
        try {
            if (originalFilename.endsWith(SUFFIX_2003)) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (originalFilename.endsWith(SUFFIX_2007)) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("格式错误");
        }
        if(workbook == null) {
            throw new ServiceException("格式错误");
        } else {
            //获取所有的工作空间的的数量
            int numOfSheet = workbook.getNumberOfSheets();

            // 遍历这些工作空间
            for(int i = 0 ; i < numOfSheet ; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                int lastRowNum = sheet.getLastRowNum();

                // 从第二行开始遍历获取值，第一行为标题
                for(int j = 1 ; j <= lastRowNum ; j++) {
                    Row row = sheet.getRow(j);
                    String deviceCode = "";
                    // 获取机器码
                    if(row.getCell(0) != null) {
                        row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                        deviceCode = row.getCell(0).getStringCellValue();
                    }
                    deviceCodeList.add(deviceCode.trim());
                }
            }
        }
        return deviceCodeList;
    }
}
